from werkzeug.security import generate_password_hash, check_password_hash
import pymysql
from pymysql import Error
import traceback


class AuthManager:
    def __init__(self):
        self.db_config = {
            'host': 'localhost',
            'user': 'root',
            'password': 'mysql',
            'database': 'weather_db',
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor
        }
        # 初始化时检查并创建管理员账户
        self.ensure_admin_exists()

    def get_db_connection(self):
        try:
            conn = pymysql.connect(**self.db_config)
            print("MySQL数据库连接成功")
            return conn
        except Error as e:
            print(f"MySQL连接错误: {str(e)}")
            print(traceback.format_exc())
            return None

    def ensure_admin_exists(self):
        """确保管理员账户存在"""
        conn = self.get_db_connection()
        if not conn:
            return

        try:
            with conn.cursor() as cursor:
                # 检查admin用户是否存在
                cursor.execute("SELECT username FROM users WHERE username = 'admin'")
                if not cursor.fetchone():
                    # 创建admin用户
                    hashed_password = generate_password_hash('admin')
                    cursor.execute(
                        "INSERT INTO users (username, password) VALUES (%s, %s)",
                        ('admin', hashed_password)
                    )
                    conn.commit()
                    print("管理员账户创建成功")
        except Error as e:
            print(f"检查管理员账户时出错: {str(e)}")
        finally:
            conn.close()

    def create_user(self, username, password):
        """创建新用户"""
        conn = self.get_db_connection()
        if not conn:
            return False

        try:
            with conn.cursor() as cursor:
                hashed_password = generate_password_hash(password)
                print(f"创建用户: username={username}, hashed_password={hashed_password}")
                cursor.execute(
                    "INSERT INTO users (username, password) VALUES (%s, %s)",
                    (username, hashed_password)
                )
            conn.commit()
            print("用户创建成功")
            return True
        except Error as e:
            print(f"创建用户失败: {str(e)}")
            print(traceback.format_exc())
            return False
        finally:
            conn.close()

    def verify_user(self, username, password):
        """验证用户登录"""
        conn = self.get_db_connection()
        if not conn:
            return None

        try:
            with conn.cursor() as cursor:
                print(f"尝试验证用户: username={username}")
                cursor.execute(
                    "SELECT username, password FROM users WHERE username = %s",
                    (username,)
                )
                user = cursor.fetchone()
                print(f"数据库查询结果: {user}")

                if user:
                    is_valid = check_password_hash(user['password'], password)
                    print(f"密码验证结果: {is_valid}")
                    if is_valid:
                        return user
                return None
        except Error as e:
            print(f"验证用户失败: {str(e)}")
            print(traceback.format_exc())
            return None
        finally:
            conn.close()

    def list_users(self):
        """列出所有用户（用于调试）"""
        conn = self.get_db_connection()
        if not conn:
            return []

        try:
            with conn.cursor() as cursor:
                cursor.execute("SELECT username, password FROM users")
                users = cursor.fetchall()
                print("当前所有用户:", users)
                return users
        except Error as e:
            print(f"获取用户列表失败: {str(e)}")
            print(traceback.format_exc())
            return []
        finally:
            conn.close()